package com.example.choupaiapp.main.activity.mine;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.adapter.BaseAdapterHelper;
import com.example.choupaiapp.common.adapter.QuickAdapter;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.DialogUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.common.view.XGridView;
import com.example.choupaiapp.main.bean.CashMoneyBean;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.bean.WechatLoginBean;
import com.example.choupaiapp.main.bean.WechatLoginUserInfoBean;
import com.example.choupaiapp.main.callback.WechatCallBack;
import com.example.choupaiapp.main.constant.Config;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.util.WechatLoginUtil;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by ASUS on 2019/11/19.
 */

public class CashActivity extends CommonActivity implements WechatCallBack {

    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.bind_nickname)
    TextView bindNickname;
    @BindView(R.id.gridview)
    XGridView gridview;
    @BindView(R.id.textview)
    TextView textview;
    private QuickAdapter<CashMoneyBean> quickAdapter;
    private UserInfoBean userInfoBean;
    private String refreshToken;
    private WechatLoginUserInfoBean mWechatLoginUserInfoBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cash);
    }

    @Override
    protected void initView() {
        setTitle("提现");

        userInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");
        refreshToken = (String) SharedPreferencesHelp.get("weChat_token", "");
        money.setText(userInfoBean.getUser().getBalance().stripTrailingZeros().toPlainString());

        List<CashMoneyBean> list = new ArrayList<>();
        CashMoneyBean cashMoneyBean = new CashMoneyBean();
        cashMoneyBean.setMoney(5);
        cashMoneyBean.setSelect(false);
        list.add(cashMoneyBean);

        CashMoneyBean cashMoneyBean1 = new CashMoneyBean();
        cashMoneyBean1.setMoney(10);
        cashMoneyBean1.setSelect(false);
        list.add(cashMoneyBean1);

        CashMoneyBean cashMoneyBean2 = new CashMoneyBean();
        cashMoneyBean2.setMoney(50);
        cashMoneyBean2.setSelect(false);
        list.add(cashMoneyBean2);

        CashMoneyBean cashMoneyBean3 = new CashMoneyBean();
        cashMoneyBean3.setMoney(100);
        cashMoneyBean3.setSelect(false);
        list.add(cashMoneyBean3);

        quickAdapter = new QuickAdapter<CashMoneyBean>(context, R.layout.item_cash_money, list) {
            @Override
            protected void convert(BaseAdapterHelper helper, CashMoneyBean item) {
                helper.setText(R.id.money, item.getMoney() + "元");
                ImageView img = helper.getView(R.id.select_img);
                if (item.isSelect()) {
                    img.setVisibility(View.VISIBLE);
                } else {
                    img.setVisibility(View.INVISIBLE);
                }
            }
        };

        gridview.setAdapter(quickAdapter);

        gridview.setOnItemClickListener((adapterView, view, i, l) -> {
            for (int j = 0; j < quickAdapter.getCount(); j++) {
                quickAdapter.getItem(j).setSelect(false);
            }
            quickAdapter.getItem(i).setSelect(true);
            quickAdapter.notifyDataSetChanged();

            if (!TextUtils.isEmpty(refreshToken) && !TextUtils.isEmpty(userInfoBean.getUser().getWechatOpenid()) && mWechatLoginUserInfoBean != null) {
                DialogUtil.getInstance().showBottomDialog(context, R.layout.dialog_cash);
                LinearLayout dialog_cash = (LinearLayout) DialogUtil.getInstance().dialog_bottom_layout;
                CircleImageView head_photo = dialog_cash.findViewById(R.id.head_photo);
                TextView name = dialog_cash.findViewById(R.id.name);
                name.setText(mWechatLoginUserInfoBean.getNickname());
                Glide.with(context)
                        .load(mWechatLoginUserInfoBean.getHeadimgurl())
                        .centerCrop()
                        .into(head_photo);

                DialogUtil.getInstance().dialog_bottom.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        for (int j = 0; j < quickAdapter.getCount(); j++) {
                            quickAdapter.getItem(j).setSelect(false);
                        }
                        quickAdapter.notifyDataSetChanged();
                    }
                });
                dialog_cash.findViewById(R.id.cash).setOnClickListener(view1 -> {
                    if (Utils.isDoubleClick()) {
                        return;
                    }
                    DialogUtil.getInstance().dialog_bottom.dismiss();
                    showDialog(context, "提现中...");
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("money", quickAdapter.getItem(i).getMoney());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.WALLET_CASH, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                        @Override
                        public void onSuccess(SendCodeBean sendCodeBean) {
                            dismissDialog();
                            DialogUtil.getInstance().showCenterDialog(context, R.layout.dialog_cash_success_fail);
                            LinearLayout dialog_cash_success_fail = (LinearLayout) DialogUtil.getInstance().dialog_center_layout;
                            ImageView img = dialog_cash_success_fail.findViewById(R.id.img);
                            TextView message = dialog_cash_success_fail.findViewById(R.id.message);
                            TextView know = dialog_cash_success_fail.findViewById(R.id.know);
                            know.setOnClickListener(view11 -> DialogUtil.getInstance().dialog_center.dismiss());
                            if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                EventBus.getDefault().post("refresh_mine");
                                EventBus.getDefault().post("refresh_wallet:" + quickAdapter.getItem(i).getMoney());
                                userInfoBean.getUser().setBalance(userInfoBean.getUser().getBalance().subtract(new BigDecimal(quickAdapter.getItem(i).getMoney())));
                                money.setText(userInfoBean.getUser().getBalance().stripTrailingZeros().toPlainString() + "");
                                img.setImageResource(R.mipmap.icon_cash_success);
                                message.setText("提现成功，预计2-3个工作日到账");
                            } else {
                                img.setImageResource(R.mipmap.icon_cash_fail);
                                message.setText(sendCodeBean.getMsg());
                            }
                        }

                        @Override
                        public void onError(Response response) {
                            super.onError(response);
                            dismissDialog();
                        }
                    });
                });
            } else {
                showImageToas("请先绑定微信");
            }
        });

    }

    @Override
    protected void initData() {
        if (!TextUtils.isEmpty(refreshToken) && !TextUtils.isEmpty(userInfoBean.getUser().getWechatOpenid())) {
            showDialog(context, null);
            finalOkGo.request(RequestType.GET, "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + Config.WEIXIN_APP_ID
                            + "&grant_type=refresh_token&refresh_token=" + refreshToken,
                    null, "refresh_token",
                    new Callback<WechatLoginBean>() {
                        @Override
                        public void onSuccess(WechatLoginBean refresh) {
                            if (refresh != null && refresh.getOpenid() != null && !TextUtils.isEmpty(refresh.getOpenid())) {
                                SharedPreferencesHelp.put("weChat_token", refresh.getRefresh_token());
                                finalOkGo.request(RequestType.GET, "https://api.weixin.qq.com/sns/userinfo?access_token="
                                                + refresh.getAccess_token()
                                                + "&openid=" + refresh.getOpenid(),
                                        null, "wechatInfo", new Callback<WechatLoginUserInfoBean>() {
                                            @Override
                                            public void onSuccess(WechatLoginUserInfoBean wechatLoginUserInfoBean) {
                                                if (wechatLoginUserInfoBean.getErrcode() != 40003) {
                                                    dismissDialog();
                                                    mWechatLoginUserInfoBean = wechatLoginUserInfoBean;
                                                    bindNickname.setText(wechatLoginUserInfoBean.getNickname());
                                                    textview.setVisibility(View.VISIBLE);
                                                } else {
                                                    dismissDialog();
                                                    showImageToas("获取用户信息失败");
                                                }
                                            }

                                            @Override
                                            public void onError(Response<String> response) {
                                                super.onError(response);
                                                dismissDialog();
                                            }
                                        });
                            } else {
                                bindNickname.setText("立即绑定");
                                textview.setVisibility(View.GONE);
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            dismissDialog();
                        }
                    });
        } else {
            bindNickname.setText("立即绑定");
            textview.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.bind_wechat})
    public void onViewClicked(View view) {
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.bind_wechat:
                if (!TextUtils.isEmpty(refreshToken) && !TextUtils.isEmpty(userInfoBean.getUser().getWechatOpenid())) {
                    if("立即绑定".equals(bindNickname.getText().toString())){
                        if (WechatLoginUtil.getInstance().isWeChatAppInstalled()) {
                            showDialog(this, "绑定中...");
                            WechatLoginUtil.getInstance().setWechatCallBack(CashActivity.this);
                            WechatLoginUtil.getInstance().wechatLogin();
                        } else {
                            showImageToas("请先安装微信客户端");
                        }
                    }
                } else {
                    if (WechatLoginUtil.getInstance().isWeChatAppInstalled()) {
                        showDialog(this, "绑定中...");
                        WechatLoginUtil.getInstance().setWechatCallBack(CashActivity.this);
                        WechatLoginUtil.getInstance().wechatLogin();
                    } else {
                        showImageToas("请先安装微信客户端");
                    }
                }
                break;
        }
    }

    @Override
    public void callBack(BaseResp baseResp) {
        String result = "";
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                textview.setVisibility(View.VISIBLE);
                SendAuth.Resp newResp = (SendAuth.Resp) baseResp;
                finalOkGo.request(RequestType.GET,
                        "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Config.WEIXIN_APP_ID
                                + "&secret=" + Config.WEIXIN_APP_SCRECT + "&code=" + newResp.code
                                + "&grant_type=authorization_code", null, "wechatLogin", new Callback<WechatLoginBean>() {
                            @Override
                            public void onSuccess(WechatLoginBean wechatLoginBean) {
                                if (wechatLoginBean != null && wechatLoginBean.getOpenid() != null && !TextUtils.isEmpty(wechatLoginBean.getOpenid())) {
                                    finalOkGo.request(RequestType.GET, "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + Config.WEIXIN_APP_ID
                                                    + "&grant_type=refresh_token&refresh_token=" + wechatLoginBean.getRefresh_token(), null, "refresh_token",
                                            new Callback<WechatLoginBean>() {
                                                @Override
                                                public void onSuccess(WechatLoginBean refresh) {
                                                    if (refresh != null && refresh.getOpenid() != null && !TextUtils.isEmpty(refresh.getOpenid())) {
                                                        JSONObject jsonObject = new JSONObject();
                                                        try {
                                                            jsonObject.put("wechatOpenid", refresh.getOpenid());
                                                        } catch (JSONException e) {
                                                            e.printStackTrace();
                                                        }
                                                        finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CHANGE_BIND_LOGIN, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                                            @Override
                                                            public void onSuccess(SendCodeBean sendCodeBean) {
                                                                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                                                    SharedPreferencesHelp.put("weChat_token", refresh.getRefresh_token());
                                                                    userInfoBean.getUser().setWechatOpenid(refresh.getOpenid());
                                                                    refreshToken = refresh.getRefresh_token();
                                                                    EventBus.getDefault().post("refresh_mine");
                                                                    finalOkGo.request(RequestType.GET, "https://api.weixin.qq.com/sns/userinfo?access_token="
                                                                                    + refresh.getAccess_token()
                                                                                    + "&openid=" + refresh.getOpenid(),
                                                                            null, "wechatInfo", new Callback<WechatLoginUserInfoBean>() {
                                                                                @Override
                                                                                public void onSuccess(WechatLoginUserInfoBean wechatLoginUserInfoBean) {
                                                                                    if (wechatLoginUserInfoBean.getErrcode() != 40003) {
                                                                                        dismissDialog();
                                                                                        mWechatLoginUserInfoBean = wechatLoginUserInfoBean;
                                                                                        bindNickname.setText(wechatLoginUserInfoBean.getNickname());
                                                                                        textview.setVisibility(View.VISIBLE);
                                                                                    } else {
                                                                                        dismissDialog();
                                                                                        showImageToas("获取用户信息失败");
                                                                                    }
                                                                                }

                                                                                @Override
                                                                                public void onError(Response<String> response) {
                                                                                    super.onError(response);
                                                                                    dismissDialog();
                                                                                }
                                                                            });
                                                                } else {
                                                                    dismissDialog();
                                                                    if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                                                    } else {
                                                                        showImageToas(sendCodeBean.getMsg());
                                                                    }
                                                                }
                                                            }

                                                            @Override
                                                            public void onError(Response response) {
                                                                super.onError(response);
                                                                dismissDialog();
                                                            }
                                                        });

                                                    } else {
                                                        dismissDialog();
                                                        showImageToas("绑定失败");
                                                    }
                                                }

                                                @Override
                                                public void onError(Response<String> response) {
                                                    super.onError(response);
                                                    dismissDialog();
                                                }
                                            });

                                } else {
                                    dismissDialog();
                                    showImageToas("绑定失败");
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                dismissDialog();
                            }
                        });
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                dismissDialog();
                result = "发送取消";
                showImageToas(result);
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                dismissDialog();
                result = "发送被拒绝";
                showImageToas(result);
                break;
            default:
                dismissDialog();
                result = "发送返回";
                showImageToas(result);
                break;
        }
    }
}
